//
//  EMMainViewController.swift
//  Hyphenate-Demo-Swift
//
//  Created by dujiepeng on 2017/6/13.
//  Copyright © 2017 dujiepeng. All rights reserved.
//

import UIKit
import Hyphenate
import UserNotifications
import SDWebImage

let kDefaultPlaySoundInterval = 3.0   
let kMessageType = "MessageType"   
let kConversationChatter = "ConversationChatter"
let kGroupName = "GroupName"
var addShareBtn = false
extension String {
    func localized(bundle: Bundle = .main, tableName: String = "Localizable") -> String {
        return NSLocalizedString(self, tableName: tableName, value: "\(self)", comment: "")
    }
}
class EMMainViewController: UITabBarController, EMChatManagerDelegate, EMGroupManagerDelegate, EMClientDelegate {
    
    private var _contactsVC : EMContactsViewController?
//    private var _calendarVC : NewCalendar?
    private var _chatsVC: EMChatsController?
//    private var _settingsVC: EMSettingsViewController?
    private var _profileVC: ProfileVC?
    
    private var lastPlaySoundDate = Date()
    
    let btn = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()
        loadViewControllers()
        NotificationCenter.default.addObserver(self, selector: #selector(setupUnreadMessageCount), name: NSNotification.Name(rawValue:KNOTIFICATION_UPDATEUNREADCOUNT), object: nil)   
        
        registerNotifications()
        EMClient.shared().getPushNotificationOptionsFromServer { (pushOptions, error) in  }
        SDImageCache.shared().maxMemoryCost = 3000 * 3000
      
    }
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        setupUnreadMessageCount()
    }
    override func viewDidAppear(_ animated: Bool) {

        super.viewDidAppear(animated)
        var bottomPadding:CGFloat = 0;
        if #available(iOS 11.0, *) {
            bottomPadding = CGFloat(view.safeAreaInsets.bottom)
        }
        if(!addShareBtn){
        btn.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - ( 90 + bottomPadding ), width: UIScreen.main.bounds.width, height: 42)
        btn.setTitle(EnStatic.getWord(keyWord: "Tell your real friends"), for: UIControlState.normal)
        btn.addTarget(self, action: #selector(share), for: UIControlEvents.touchUpInside)
        btn.backgroundColor = PaleGreyTwoColor
        btn.setTitleColor(KermitGreenTwoColor, for: UIControlState.normal)
        self.view.addSubview(btn)
            addShareBtn = true
        }
    }
    
    //Mark add
    @objc func share() {
        let firstActivityItem = "https://www.curtainups.com/"
        let secondActivityItem : NSURL = NSURL(string: "https://www.curtainups.com/")!
        
        let image : UIImage = UIImage(named: "icon_shhhhh")!
        let activityViewController : UIActivityViewController = UIActivityViewController(
            activityItems: [firstActivityItem, secondActivityItem, image], applicationActivities: nil)
        
        // Anything you want to exclude
        activityViewController.excludedActivityTypes = [
            UIActivityType.postToWeibo,
            UIActivityType.postToFacebook,
            UIActivityType.message,
            UIActivityType.mail,
        ]
        
        self.present(activityViewController, animated: true, completion: nil)
    }
    
    // MARK: - Notification Registration
    func registerNotifications() {
        unregisterNotifications()   
        EMClient.shared().add(self, delegateQueue: nil)   
        EMClient.shared().chatManager.add(self, delegateQueue: nil)   
        EMClient.shared().groupManager.add(self, delegateQueue: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(statusBarChange), name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: nil)
    }
    
    func unregisterNotifications() {
        NotificationCenter.default.removeObserver(self)
        EMClient.shared().removeDelegate(self)   
        EMClient.shared().chatManager.remove(self)   
        EMClient.shared().groupManager.removeDelegate(self)   
    }
    
    @objc func statusBarChange(){
        
        var bottomPadding:CGFloat = 0;
        if #available(iOS 11.0, *) {
            bottomPadding = CGFloat(view.safeAreaInsets.bottom)
        }
        
        let height =  UIApplication.shared.statusBarFrame.height
        var statusHeight:CGFloat = 0.0
        if(height <= 20)
        {
            statusHeight = 0.0
        }
        else
        {
            statusHeight = 20
        }
        
         btn.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - ( 90 + bottomPadding ) - statusHeight, width: UIScreen.main.bounds.width, height: 42)
    }
    
    // MARK: - viewControlle
    func loadViewControllers() {
        
        _contactsVC = EMContactsViewController()   
        _contactsVC?.tabBarItem = UITabBarItem.init(title: "Contacts".localized(), image: UIImage(named: "icons_tab_book"), tag: 1)
        _contactsVC?.tabBarItem.selectedImage = UIImage(named:"icons_tab_book_pre")
//        unSelectedTapTabBarItems(item: _contactsVC?.tabBarItem)
//        selectedTapTabBarItems(item: _contactsVC?.tabBarItem)
        
//        let storyboard1 = UIStoryboard.init(name: "NewCalendar", bundle: nil)
//        _calendarVC  = storyboard1.instantiateViewController(withIdentifier: "NewCalendar") as? NewCalendar
//        _calendarVC?.tabBarItem = UITabBarItem.init(title: "Schedules".localized(), image: UIImage(named: "icon_tab_calendar"), tag: 2)
//        _calendarVC?.tabBarItem.selectedImage = UIImage(named:"icon_tab_calendar_pre")
//        unSelectedTapTabBarItems(item: _calendarVC?.tabBarItem)
//        selectedTapTabBarItems(item: _calendarVC?.tabBarItem)
        
        
        _chatsVC = EMChatsController()   
        _chatsVC?.tabBarItem = UITabBarItem.init(title: "Chats".localized(), image: UIImage(named: "icon_tab_chat"), tag: 0)
        _chatsVC?.tabBarItem.selectedImage = UIImage(named:"icon_tab_chat_pre")
//        unSelectedTapTabBarItems(item: _chatsVC?.tabBarItem)
//        selectedTapTabBarItems(item: _chatsVC?.tabBarItem)
        /// FIXME:
        
        let storyboard = UIStoryboard.init(name: "ProfileVC", bundle: nil)
        _profileVC  = storyboard.instantiateInitialViewController() as? ProfileVC
        _profileVC?.tabBarItem = UITabBarItem.init(title: "Profile".localized(), image: UIImage(named:"icon_tab_user"), tag: 3)
        _profileVC?.tabBarItem.selectedImage = UIImage(named:"icon_tab_user_pre")
        viewControllers = [_chatsVC!,_contactsVC!,_profileVC!]
        selectedIndex = 0
        _chatsVC?.setupNavigationItem(navigationItem: navigationItem)
        EMChatDemoHelper.shareHelper.contactsVC = _contactsVC
//        EMChatDemoHelper.shareHelper.calendarVC = _calendarVC
        EMChatDemoHelper.shareHelper.chatsVC = _chatsVC
//        EMChatDemoHelper.shareHelper.settings = _profileVC
    }

    
    @objc public func setupUnreadMessageCount() {
        let conversations = EMClient.shared().chatManager.getAllConversations()   
        var unreadCount = 0   
        for conversation in conversations! {
            
            unreadCount += (Int)((conversation as! EMConversation).unreadMessagesCount)
            
        }
        
        if _chatsVC != nil {
            if unreadCount > 0 {
                _chatsVC?.tabBarItem.badgeValue = "\(unreadCount)"   
            } else {
                _chatsVC?.tabBarItem.badgeValue = nil   
            }
        }
        
        UIApplication.shared.applicationIconBadgeNumber = unreadCount
    }
    
    // MARK: - UITabbarDelegate
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        
        btn.isHidden = item.tag != 0
       
    
        tabBar.items?.forEach({ (item) in
            item.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11),NSAttributedStringKey.foregroundColor:CoolGrayColor], for: UIControlState.normal)
        })
        item.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11),NSAttributedStringKey.foregroundColor:KermitGreenTwoColor], for: UIControlState.normal)
        if item.tag == 0 {
            title = "Chat".localized()
            
            _chatsVC?.setupNavigationItem(navigationItem: navigationItem)
        }
        
        if item.tag == 1 {
            title = "Contacts".localized()

            _contactsVC?.setupNavigationItem(navigationItem: navigationItem)
        }
//        if item.tag == 2 {
//            title = "Schedules".localized()
//            _calendarVC?.setupNavigationItem(navigationItem: navigationItem)
//
//        }
        if item.tag == 3 {
            title = "Settings".localized()
            clearNavigationItem()
        }
    }
    
    // MARK: - EMChatManagerDelegate
    func messagesDidReceive(_ aMessages: [Any]!) {
        setupUnreadMessageCount()   
        for msg in aMessages {
            let state = UIApplication.shared.applicationState   
            switch state {
            case UIApplicationState.active,UIApplicationState.inactive:
                playSoundAndVibration()   
                break
            case UIApplicationState.background:
                showNotificationWithMessage(msg: (msg as! EMMessage))   
                break
            }
        }
    }
    
    func conversationListDidUpdate(_ aConversationList: [Any]!) {
        setupUnreadMessageCount()   
    }
    
    func connectionStateDidChange(_ aConnectionState: EMConnectionState) {
        _chatsVC?.networkChanged(connectionState: aConnectionState)
    }
    
    func userAccountDidLoginFromOtherDevice() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue:KNOTIFICATION_LOGINCHANGE), object: NSNumber(value: false))   
    }
    
    func userAccountDidRemoveFromServer() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue:KNOTIFICATION_LOGINCHANGE), object: NSNumber(value: false))   
    }
    
    func clearNavigationItem() {
        navigationItem.titleView = nil
        navigationItem.leftBarButtonItem = nil
        navigationItem.rightBarButtonItem = nil   
    }
    
    // MARK - private
    
    private func conversationTypeFromMessageType(chatType:EMChatType) -> EMConversationType {
        var type = EMConversationTypeChat   
        switch chatType {
        case EMChatTypeChat: type = EMConversationTypeChat   
        break   
        case EMChatTypeGroupChat: type = EMConversationTypeGroupChat   
        break   
        case EMChatTypeChatRoom: type = EMConversationTypeChatRoom   
        break   
        default: type = EMConversationTypeChat   
        break   
        }
        
        return type   
    }
    
    func playSoundAndVibration() {
        let timeInterval = Date().timeIntervalSince(lastPlaySoundDate)
        if timeInterval < 3.0 {
            return
        }
        
        lastPlaySoundDate = Date()
        EMCDDeviceManager.sharedInstance().playNewMessageSound()
        EMCDDeviceManager.sharedInstance().playVibration()
    }
    
    func showNotificationWithMessage(msg: EMMessage) {
        let options = EMClient.shared().pushOptions
        var alertStr = ""
        if options?.displayStyle == EMPushDisplayStyleMessageSummary {
            let msgBody = msg.body
            
            var msgStr = ""   
            switch msgBody!.type {
            case EMMessageBodyTypeText:
                msgStr = (msgBody as! EMTextMessageBody).text   
                break   
            case EMMessageBodyTypeImage:
                msgStr = "[Image]"
                break   
            case EMMessageBodyTypeLocation:
                msgStr = "[Location]"
                break   
            case EMMessageBodyTypeVoice:
                msgStr = "[Voice]"
                break   
            case EMMessageBodyTypeVideo:
                msgStr = "[Video]"
                break   
            case EMMessageBodyTypeFile:
                msgStr = "[File]"
                break   
            default:
                msgStr = ""
                break   
            }
//            alertStr = EMUserProfileManager.sharedInstance.getNickNameWithUsername(username: msg.from) + ":" + msgStr
            alertStr = "You have a new message from:".localized() + EMUserProfileManager.sharedInstance.getNickNameWithUsername(username: msg.from)
            
        } else {
            alertStr = "You have a new message".localized()
        }
        
        let timeInterval = Date().timeIntervalSince(lastPlaySoundDate)
        var playSound = false
        if timeInterval > 3.0 {
            lastPlaySoundDate = Date()
            playSound = true
        }
        if #available(iOS 10.0, *) {
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
            let content = UNMutableNotificationContent()
            content.body = alertStr
            if playSound {
                content.sound = UNNotificationSound.default()
            }
            let request = UNNotificationRequest(identifier: msg.messageId, content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }else if #available(iOS 8.0, *){
            let notification = UILocalNotification()
            notification.fireDate = Date()
            notification.alertBody = alertStr
            notification.alertAction = "Open"
            notification.timeZone = NSTimeZone.default
            if playSound {
                notification.soundName = UILocalNotificationDefaultSoundName
            }
            UIApplication.shared.scheduleLocalNotification(notification)
        }
    }
}
